package com.chenc.javathreads.TestJavaLock.synchronizecount;

import lombok.Synchronized;

/**
 * @ClassName
 * @Describtion: 锁对象 synchronized (this) {number++;}
 * @Author:Chenc
 * @Date:2023/11/23 16:49
 * @Version 1.0
 */
public class SynchronizedValiable3 {
    //变量
    private static int number = 0;
    private Object o;

    static class Counter {
        //循环次数
        private static int MAX_COUNT = 1000000;

        //++方法
        public void incr() {
            System.out.println("start incr");
            for (int i = 0; i < MAX_COUNT; i++) {
                number++;
            }
        }

        //--方法
        public void decr() {
            System.out.println("start decr");
            for (int i = 0; i < MAX_COUNT; i++) {

                number--;
            }
        }

        public void print() {
            System.out.println("print");
        }

    }

    public static void main(String[] args) throws InterruptedException {
        Object o = new Object();
        Counter counter = new Counter();
        Thread t1 = new Thread(() -> {
            synchronized (o) {
                counter.incr();
            }
        });
        t1.start();
        Thread t2 = new Thread(() -> {
            synchronized (o) {
                counter.decr();
            }

        });
        Counter c3 = new Counter();
        Thread t3 = new Thread(() -> {
            c3.print();
        });
        t3.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(" 最终的结果：" + number);
    }
}

